package com.evaluation_system.service.impl;

import com.evaluation_system.Repository.NonceRepository;
import com.evaluation_system.pojo.entity.RequestNonce;
import com.evaluation_system.service.NonceService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service

public class NonceServiceImpl implements NonceService {
    @Autowired
    private NonceRepository nonceRepository;

    @Override
    public boolean isUsed(String nonce) {
        return nonceRepository.existsByNonce(nonce);
    }

    @Override
    public void markUsed(String nonce) {
        RequestNonce entity = new RequestNonce();
        entity.setNonce(nonce);
        entity.setCreatedAt(LocalDateTime.now());
        nonceRepository.save(entity);
    }

    @Override
    @Transactional
    public void clearExpiredNonces() {
        LocalDateTime expireTime = LocalDateTime.now().minusMinutes(120);
        nonceRepository.deleteAllByCreatedAtBefore(expireTime);
    }
}
